<template>
    <div>
        <h3>合同生成</h3>
        <button @click="generateContract">生成合同</button>
        <div v-if="contractContent">
            <h4>合同内容</h4>
            <pre>{{ contractContent }}</pre>
            <button @click="downloadContract">下载合同</button>
            <router-link
                :to="{ name: 'ContractDetail', query: { content: contractContent, packageName: selectedPackage.name } }">查看合同详情</router-link>
        </div>
    </div>
</template>

<script>
import contractTemplate from '@/assets/contract-template.txt';

export default {
    props: {
        selectedPackage: {
            type: Object,
            default: null
        },
        selectedSkus: {
            type: Object,
            default: () => ({})
        },
        totalPrice: {
            type: Number,
            default: 0
        }
    },
    data() {
        return {
            contractContent: ''
        };
    },
    methods: {
        async generateContract() {
            if (!this.selectedPackage) return;

            try {
                const response = await fetch(new URL(contractTemplate, import.meta.url));
                let template = await response.text();

                template = template.replace('{{packageName}}', this.selectedPackage.name);
                template = template.replace('{{packageModel}}', this.selectedPackage.model);
                template = template.replace('{{totalPrice}}', this.totalPrice.toString());

                Object.keys(this.selectedSkus).forEach(skuGroup => {
                    const skuKey = this.selectedSkus[skuGroup];
                    const skuName = this.selectedPackage.skus[skuGroup][skuKey].name;
                    template = template.replace(`{{${skuGroup}}}`, skuName);
                });

                this.contractContent = template;
            } catch (error) {
                console.error('生成合同失败：', error);
            }
        },
        downloadContract() {
            if (!this.contractContent) return;

            const blob = new Blob([this.contractContent], { type: 'text/plain' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `contract_${this.selectedPackage.name}.txt`;
            a.click();
            URL.revokeObjectURL(url);
        }
    }
};
</script>